<script lang="ts" setup>
import { addCardApi, getCardDetailAPI, updateCardAPI } from '@/apis/card';
import { PaymentMethod } from '@/enum/card';
import router from '@/router';
import type {  CardParams,  CardPayParams, cardSubmit } from '@/types/card';
import type { FormRules } from 'element-plus';
import { ca, el } from 'element-plus/es/locales.mjs';
import { computed, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
// 获取月卡信息id
const route = useRoute()
const cardId = computed(()=>{
    return route.query.id as string
})  
// 车辆信息,双向绑定
const carInfo = ref<CardParams>({
    personName:'',
    phoneNumber:'',
    carNumber:'',
    carBrand:'',
})
//表单校验
const formRef = ref()
const validateCarNum = (rule:any,value:string,callback:Function)=>{
    // 车牌号正则
      const plateNumberRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使]{1}[A-Z]{1}[A-Z0-9]{5,6}$/
      if(!plateNumberRegex.test(value)){
        callback(new Error('请输入正确格式的车牌号'))
      }else{
        callback()
      }
}
// 校验规则
const rules = reactive<FormRules<CardParams>>({
    personName: [
      { required: true, message: '请输入车主姓名', trigger: 'blur' },
    ],
    phoneNumber: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      { pattern: /^1[34578]\d{9}$/, message: '请输入正确格式手机号' }
    ],
    carNumber: [
      { required: true, message: '请输入车辆号码', trigger: 'blur' },
    //   自定义校验规则
      {
        validator: validateCarNum, trigger: 'blur' 
      }
    ],
    carBrand: [
        {
      required: true, message: '请输入车辆品牌', trigger: 'blur'
    },
    ]
})

// 缴费信息表单
const payInfo = ref<CardPayParams>({
    time:[],
    //支付金额
    paymentAmount:0,
    paymentMethod: undefined
})
// 支付方式数组
const paymentMethodOptions = ref([{
    name:'支付宝',
    value:PaymentMethod.Alipay
},
{
    name:'微信',
    value:PaymentMethod.WeChat
},
{
    name:'现金',
    value:PaymentMethod.Cash
}
])
// 缴费信息表单校验
const payRules = reactive<FormRules<CardPayParams>>({
    time: [
      { required: true, message: '请选择日期', trigger: 'blur' },
    ],
    paymentAmount: [
      { required: true, message: '请输入支付金额', trigger: 'blur' },
    ]
  })
  const payRef = ref()

  //提交数据
  const onSubmit = ()=>{
    //校验表单
    formRef.value.validate((valid:boolean)=>{
        if(valid){
            payRef.value.validate(async (valid:boolean)=>{
                if(valid){
                    // 提交数据
                    const data={
                         ...carInfo.value,
                         paymentAmount: payInfo.value.paymentAmount,
                        paymentMethod: payInfo.value.paymentMethod?.toString(),
                         cardStartDate: payInfo.value.time[0],
                    cardEndDate: payInfo.value.time[1],
                    } as unknown as cardSubmit
                    // 根据id判断是新增还是修改请求
                    if(cardId.value){
                        data.rechargeId = payInfo.value.rechargeId
                        await updateCardAPI(data)
                    }else{
                        await addCardApi(data)
                    }
                    router.back()
                }
            })
        }
    })
  }

//   获取月卡详情
const getDetail = async()=>{
    const res = await getCardDetailAPI(cardId.value)
    const { carInfoId, personName, phoneNumber, carNumber, carBrand } = res.data
    carInfo.value = {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        carInfoId
    }
    // 缴费信息
    const { rechargeId, cardStartDate, cardEndDate, paymentAmount, paymentMethod } = res.data
    payInfo.value = {
        time: [cardStartDate, cardEndDate],
        paymentAmount,
        paymentMethod: paymentMethod,
        rechargeId
    }
}
onMounted(()=>{
    if(cardId.value){
        getDetail()
    }
})
</script>
<template>
    <div class="add-card">
      <header class="add-header">
        <el-page-header content="增加月卡" @back="$router.back()" />
      </header>
      <main class="add-main">
        <div class="form-container">
          <div class="title">车辆信息</div>
          <div class="form">
            <el-form label-width="100px" :model="carInfo" ref="formRef" :rules="rules">
              <el-form-item label="车主姓名" prop="personName">
                <el-input v-model="carInfo.personName"/>
              </el-form-item>
              <el-form-item label="联系方式" prop="phoneNumber">
                <el-input v-model="carInfo.phoneNumber" />
              </el-form-item>
              <el-form-item label="车辆号码" prop="carNumber">
                <el-input v-model="carInfo.carNumber" />
              </el-form-item>
              <el-form-item label="车辆品牌" prop="carBrand">
                <el-input v-model="carInfo.carBrand" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="form-container">
          <div class="title">最新一次月卡缴费信息</div>
          <div class="form">
            <el-form label-width="100px" :model="payInfo" ref="payRef" :rules="payRules">
              <el-form-item label="有效日期" prop="time">
                <el-date-picker v-model="payInfo.time" value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" />
              </el-form-item>
              <el-form-item label="支付金额" prop="paymentAmount">
                <el-input-number v-model="payInfo.paymentAmount" :precision="2" :step="0.1" :max="999999999" :min="0" />
              </el-form-item>
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select v-model="payInfo.paymentMethod">
                  <el-option v-for="item in paymentMethodOptions" :key="item.value" :value="item.value" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
  
      </main>
      <footer class="add-footer">
        <div class="btn-container">
          <el-button>重置</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </div>
      </footer>
    </div>
  </template>
  
  <style scoped lang="scss">
  .add-card {
    background-color: #f4f6f8;
    height: 100vh;
  
    .add-header {
      display: flex;
      align-items: center;
      padding: 0 20px;
      height: 64px;
      background-color: #fff;
  
      .left {
        span {
          margin-right: 4px;
        }
  
        .arrow {
          cursor: pointer;
        }
      }
  
      .right {
        text-align: right;
      }
    }
  
    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;
  
      .form-container {
        background-color: #fff;
  
        .title {
          height: 60px;
          line-height: 60px;
          padding-left: 20px;
        }
  
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
  
          .el-form {
            display: flex;
            flex-wrap: wrap;
  
            .el-form-item {
              width: 50%;
            }
          }
        }
      }
  
      .preview {
        img {
          width: 100px;
        }
      }
    }
  
    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>